from Common import Request, Config
import re, time, os, allure
from Params.params import GetParameter
from Common import Log


class OBSYS:
    def __init__(self):
        self.data = GetParameter('OB').get_params()
        self.s = Request.Request()
        self.log = Log.MyLog()
        self.env = Config.Config().get_conf('comm', 'env')
        self.login_host = Config.Config().get_conf(self.env, 'ob_login_host')
        self.host = Config.Config().get_conf(self.env, 'ob_host')

    @allure.step('登录OB系统')
    def login(self):
        self.log.info('开始执行OB系统相关操作：登陆OB_01')
        url_1 = self.data[1]['url'] % (self.login_host,self.host)
        print(url_1)
        res_1 = self.s.get_request(url_1)
        lt = re.findall(r'name="lt" value="(.*)"', res_1['text'])[0]
        execution = re.findall(r'name="execution" value="(.*)"', res_1['text'])[0]
        self.log.info('开始执行OB系统相关操作：登陆OB_02')
        url_2 = url_1
        data_2 = self.data[2]['data']
        data_2['username'] = Config.Config().get_conf(self.env, 'ob_username')
        data_2['password'] = Config.Config().get_conf(self.env, 'ob_password')
        data_2['lt'] = lt
        data_2['execution'] = execution
        res_2 = self.s.post_request(url_2, data_2)
        self.log.info(str(data_2))
        self.log.info(str(res_2))
        print('OB登录 完成')

    @allure.step('通过订单号获取取件单')
    def setDispatchBill(self, OrderNo):
        self.log.info('开始执行OB系统相关操作：OB客服系统，通过订单号获取取件单')
        url_3 = 'http://' + self.host + self.data[3]['url']
        data_3 = self.data[3]['data']
        data_3 = data_3 % OrderNo
        time.sleep(5)
        res_3 = self.s.get_request(url_3, data_3)
        count = 1
        while res_3['body']['error'] == 0 and res_3['body']['data'] is None and count <= 3:
            self.log.info("通过订单号未获取到取件单信息，尝试进行派单操作")
            url_dispatch = 'http://' + self.host + self.data[6]['url']
            data_dispatch = self.data[6]['data']
            data_dispatch['orderNo'] = OrderNo
            data_dispatch['PickupDt'] = str(time.strftime('%Y-%m-%d 00:00:00', time.localtime()))
            res_dispatch = self.s.post_request(url_dispatch, data_dispatch)
            self.log.info(str(res_dispatch['text']))

            self.log.info('通过订单号未获取到取件单号，准备进行第%s次重试' % count)
            res_3 = self.s.get_request(url_3, data_3)
            count += 1
        self.log.info(str(data_3))
        self.log.info(res_3['text'])
        self.log.info('开始执行OB系统相关操作：OB客服系统，根据用户名获取用户ID')
        url_getObserverByKey = 'http://' + self.host + self.data[8]['url'] % Config.Config().get_conf(self.env, 'account')
        res_getObserverByKey = self.s.get_request(url_getObserverByKey)
        self.log.info('开始执行OB系统相关操作：OB客服系统，设置取件人')
        url_4 = 'http://' + self.host + self.data[4]['url']
        data_4 = self.data[4]['data']
        data_4['BillNo'] = res_3['body']['data']['dispatchBillNo']
        data_4['PickupDt'] = time.strftime('%Y-%m-%d 00:00:00', time.localtime())
        data_4['PickupStaffId'] = int(res_getObserverByKey['body']['data']['items'][0]['id'])
        res_4 = self.s.post_request(url_4, data_4)
        self.log.info(str(data_4))
        self.log.info(res_4['text'])
        print('通过订单号获取取件单 完成')

        return res_3['body']['data']['dispatchBillId']

    @allure.step('编辑物流信息')
    def editLogistics(self, orderNo):
        logis_url = 'http://' + self.host + self.data[7]['url']
        logis_data = self.data[7]['data']
        logis_data['orderNo'] = logis_data['expressNo'] = orderNo
        logis_res = self.s.post_request(logis_url, logis_data)
        self.log.info(str(logis_data))
        self.log.info(logis_res['text'])
        print('编辑物流信息 完成')

    @allure.step('获取订单基础信息，并写入文件')
    def getOrderInfo(self, OrderNo):
        url_5 = 'http://' + self.host + self.data[5]['url']
        data_5 = self.data[5]['data']
        data_5 = data_5 % OrderNo
        res_5 = self.s.get_request(url_5, data_5)
        self.log.info(str(data_5))
        self.log.info(res_5['text'])
        orderInfo_path = os.path.dirname(os.path.dirname(__file__)) + '\\Params\\Param\\orderInfo.txt'

        # 根据回收方式的不同，orderInfo文件中写入不同的内容
        # 回收方式为物流：【订单号】
        # 回收方式为门店：【大订单号，订单号】
        # 回收方式为上门：【大订单号，订单号，取件单ID】
        with open(orderInfo_path, 'w') as f:
            if res_5['body']['data']['pickupType'] == 4:
                self.editLogistics(OrderNo)
                f.write(OrderNo)
            elif res_5['body']['data']['pickupType'] == 5:
                f.write(res_5['body']['data']['recycleOrderNo'] + ',' + OrderNo)
            else:
                dispatchBillId = self.setDispatchBill(OrderNo)
                f.write(res_5['body']['data']['recycleOrderNo'] + ',' + OrderNo + ',' + str(dispatchBillId))
        print('获取订单基础信息，并写入文件 完成')

    @allure.step('从文件中读取订单信息')
    def readOrderInfo(self):
        orderInfo_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "\\Params\\Param\\orderInfo.txt"
        self.log.info(orderInfo_path)
        with open(orderInfo_path, "r") as f:
            orderInfo = f.read()
        info = orderInfo.split(',')
        print('从文件中读取订单信息 完成')

        return info


if __name__ == '__main__':
    o = OBSYS()
    orderinfos = o.readOrderInfo()
    o.login()
    o.getOrderInfo('20181217170555307644')
